#----------------------------------------------------------------------------------------
#
# Sample usage:
#    
#  Download the WebClient with Cookies
#    PS> download-webclient-with-cookies
#    
#  Send me spam
#    PS> spam-adamdotcom
#
# Adam Kahtava - http://adam.kahtava.com/ - MIT Licensed    
#
#-----Maintained by Adam Kahtava---------------------------------------------------------

function global:download-webclient-with-cookies(){
  download-file 'http://adamdotcom-services.googlecode.com/svn/trunk/AdamDotCom.Common.Service/Final-Assemblies/AdamDotCom.WebClientWithCookies.dll'
}

function global:spam-adamdotcom(){
  trap [Exception]{
    write-host $_.Exception.Message
    break;
  }
    
  # Load the assembly containing WebClientWithCookies and RegexUtilities
  [Reflection.Assembly]::LoadFile((Resolve-Path "AdamDotCom.WebClientWithCookies.dll")) | out-null
  
  # Load the assembly containing System.Web.HttpUtilitiy
  [void][Reflection.Assembly]::LoadWithPartialName("System.Web") | out-null  
    
  # create a new instance of the HTTP Web Client that supports cookies
  $webClient = New-Object AdamDotCom.Common.Service.Utilities.WebClientWithCookies
  
  # download Adam's contact page that contains the Anti CRSF Token
  [void] $webClient.DownloadData("http://adam.kahtava.com/contact")
  
  # create a new regular expression to grab the Anti CRSF Token - since this is an MVC site our token is named "__RequestVerificationToken_Lw__"
  $regex = "__RequestVerificationToken_Lw__=(?<CRSF_Token>[^;]+)"
  $match = [regex]::matches($webClient.ResponseHeaders["Set-Cookie"], $regex)[0]
  $antiCrsfToken = $match.Groups["CRSF_Token"].Captures[0].Value

  write-host "`nYour Anti CRSF Token is: " $antiCrsfToken
  
  # construct the message including the Anti CSRF Token
  $message = "__RequestVerificationToken=" + [System.Web.HttpUtility]::UrlEncode($antiCrsfToken) + 
             "&fromName=Johnathon Fink" + 
             "&fromAddress=prancesw@rmcres.com" + 
             "&subject=Call for your diploma now" + 
             "&body=Is your lack of a degree..."
    
  # drown Adam in spam-spam-spam
  $webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
  [void] $webClient.UploadData("http://adam.kahtava.com/contact/send", "POST", ([System.Text.Encoding]::UTF8.GetBytes($message)));

  write-host "`nSuccess!!! Your spam has been sent.`n"
  
  $webClient = $null
}

# My curl equivelent method poached from http://adamdotcom-script.googlecode.com/svn/trunk/Scripts/PowerShell/Development-Utilities.ps1
function global:download-file([string] $urlPath) {
  $urlSplit = $urlPath.split('/')
  $filename = (Resolve-Path .\).ToString() + '\' + $urlSplit[$urlSplit.length - 1]
  $webclient = New-Object "System.Net.WebClient"
  $webclient.DownloadFile($urlPath, $filename)
  return $filename
}